﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SpringGraphTwitterExample.Twitter;
using SpringGraph;
using SpringGraphTwitterExample.Entities;
using System.Windows.Browser;
using SpringGraphTwitterExample.Windows;

namespace SpringGraphTwitterExample
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            var win = new UsernameWindow();
            win.Closed += new EventHandler(win_Closed);
            win.Show();
        }

        void win_Closed(object sender, EventArgs e)
        {
            var win = sender as UsernameWindow;

            var twitterClient = new TwitterClient();
            twitterClient.GetUserAndFriendsCompleted += new EventHandler<GetUserAndFriendsEventArgs>(twitterClient_GetUserAndFriendsCompleted);
            twitterClient.GetUserAndFriendsAsync(win.TextUserName.Text);
        }

        void twitterClient_GetUserAndFriendsCompleted(object sender, GetUserAndFriendsEventArgs e)
        {
            var g = new Graph();

            foreach (var user in e.Users)
            {
                g.Add(new Item() { DataContext = user });
            }

            foreach (var userItem in g.Nodes)
            {
                var user = userItem.DataContext as User;

                var friends = g.Nodes.Where(node => user.FriendsIds.Contains(((User)node.DataContext).Id));

                foreach (var friendItem in friends)
                {
                    g.Link(userItem, friendItem);
                }
            }

            Graph.DataProvider = g;
        }

        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
            var link = sender as HyperlinkButton;
            var user = link.DataContext as User;

            HtmlPage.Window.Navigate(new Uri("http://twitter.com/" + user.ScreenName), "_blank");
        }

    }
}
